//
//  MBSendShowController.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/9/26.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//
#import "MBFeelView.h"
#import "MBSendShowController.h"
#import "MBRecordController.h"
#import "MBPlayShowController.h"
#import "AFNetworking.h"
#import "UIButton+WebCache.h"
#import "UpdateProgressView.h"
#import "MBRecordController.h"

typedef enum {
    IdentityType_baby = 10,
    IdentityType_zhubo,
    
}IdentityType;

@interface MBSendShowController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationBarDelegate,UINavigationControllerDelegate,UITextViewDelegate,UpdateProgressViewDelegate> {
    UIImage                 *_showImg;
    NSString                *_picUrl;
    NSString                *_audioUrl;
    NSString                *_capacity;
    NSNumber                *_showType;
    
    AVAudioPlayer           *_audioPlayer;
    UITextField             *_textField;
    UpdateProgressView      *_updateView;
    AVAudioSession          *_audioSession;
}


@property (nonatomic,assign)IdentityType    identityType;
@property (nonatomic, strong) MBFeelView *feelView;
@property (nonatomic, strong) UIButton *saveBtn;
@property (nonatomic, strong) UIButton *changeBtn;
@end

@implementation MBSendShowController
{
    UITableView *_tableView;
    UIImageView *_imgView;
    UILabel     *_showLb;
    UIButton    *_showBtn;
    UILabel     *_countLb;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"发布亲子秀";
    
    _capacity = @"";
    _showType = @1;
    
    [self setupNavBar];
    [self setupUI];
    
}
- (void)setupNavBar {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"fanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(navigationBackButton)];
    if (ISIPAD) {
        UIButton *sendQZShowBt = [UIButton buttonWithType:UIButtonTypeCustom];
        sendQZShowBt.frame = CGRectMake(0, 0, 60, 30);
        [sendQZShowBt setImage:[UIImage imageNamed:@"wenhao"] forState:UIControlStateNormal];
        [sendQZShowBt setImage:[UIImage imageNamed:@"wenhao"] forState:UIControlStateHighlighted];
        [sendQZShowBt setImageEdgeInsets:UIEdgeInsetsMake(-40, 0, -40, -40)];
        [sendQZShowBt addTarget:self action:@selector(help) forControlEvents:UIControlEventTouchUpInside];
        [self setRightBarItems:sendQZShowBt];
    }


}

-(void)navigationBackButton {
    BOOL isBack = NO;
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[MBRecordController class]]) {
            isBack = YES;
            MBRecordController *revise =(MBRecordController *)controller;
            [self.navigationController popToViewController:revise animated:YES];
        }
    }
    
    if (isBack == NO) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"MBSENDSHOW_NOTIFICATION" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)onCompleteUpdateProgeressView:(UpdateProgressView *)view
{
    if (view.type == UpdateProgressViewType_Success) {
        [self navigationBackButton];
    } else {
        [ErrorMessage showErrorMessage:@"上传失败，请重试!" inView:self.view];
    }
}

//点击帮助
- (void)help {
    MBPlayShowController *playShowVC = [[MBPlayShowController alloc] init];
    [self.navigationController pushViewController:playShowVC animated:YES];
}


- (void)setupUI {
    NSLog(@"date==%@",_dataDic);
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideTheKeyBoard)];
    [_tableView addGestureRecognizer:tap];
    
    //顶部视图*********************************
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0,20*PERCEN_HEIGHT ,SCREEN_WIDTH , 140*PERCEN_HEIGHT)];
 
    [_tableView addSubview:topView];
    topView.backgroundColor = [UIColor whiteColor];
    

  
 


    UIImageView *iconHeaderView = [[UIImageView alloc]initWithFrame:CGRectMake(25*PERCEN, 15*PERCEN_HEIGHT, 110*PERCEN_HEIGHT, 110*PERCEN_HEIGHT)];
    iconHeaderView.backgroundColor = [UIColor clearColor];

    if (ISIPAD) {
        iconHeaderView.frame = CGRectMake(460*PERCEN, 15*PERCEN_HEIGHT, 110*PERCEN_HEIGHT, 110*PERCEN_HEIGHT);
    }
    if (_isFormFreedom) {
        iconHeaderView.image = [UIImage imageNamed:@"qzx_player_icon"];
    } else {
        [iconHeaderView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,[_dataDic objectForKey:@"PicPath"]]] placeholderImage:[UIImage imageNamed:@"qzx_player_icon"]];
    }
    [topView addSubview:iconHeaderView];
    iconHeaderView.layer.cornerRadius = 3.;
    iconHeaderView.layer.masksToBounds = YES;
    
    
    UIButton *iconImageView = [UIButton buttonWithType:UIButtonTypeCustom];
    iconImageView.frame = iconHeaderView.frame;
    if (ISIPAD) {
        iconImageView.backgroundColor = [UIColor clearColor];
    } else {
        iconImageView.backgroundColor = [UIColorFromHex(0x000000) colorWithAlphaComponent:.25];
    }
    iconImageView.alpha = 1.;

    [iconImageView setImage:[UIImage imageNamed:@"bofang_fb"] forState:UIControlStateNormal];
    [iconImageView setImage:[UIImage imageNamed:@"zanting_fb"] forState:UIControlStateSelected];
    [iconImageView addTarget:self action:@selector(onChangePlauMusicStatus:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:iconImageView];
    iconImageView.layer.cornerRadius = 3.;
    iconImageView.layer.masksToBounds = YES;
    
    UILabel *titleLb = [[UILabel alloc] initWithFrame:CGRectMake(iconImageView.right, topView.height/2-10*PERCEN_HEIGHT, 34+20*PERCEN, 40*PERCEN_HEIGHT)];
    if (ISIPAD) {
        titleLb.frame=CGRectMake(iconImageView.right+20*PERCEN, topView.height/2-10*PERCEN_HEIGHT, 60*PERCEN, 40*PERCEN_HEIGHT);
    }
    titleLb.backgroundColor = [UIColor clearColor];
    titleLb.text = @"标题:";
    if (ISIPAD) {
        titleLb.font = [UIFont systemFontOfSize:30*PERCEN];
        titleLb.textColor = UIColorFromHex(0x333333);
    }else{
    titleLb.font = [UIFont systemFontOfSize:13.f];
    titleLb.textColor = [UIColor blackColor];
    titleLb.textAlignment = NSTextAlignmentRight;
    }
  
    [topView addSubview:titleLb];
    
    NSString *AudioName = [_dataDic objectForKey:@"AudioName"];
    AudioName = [AudioName componentsSeparatedByString:@"."][0];
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(titleLb.right, titleLb.top+(40*PERCEN-16)/2., 200, 16)];
    if (ISIPAD) {
        _textField.frame=CGRectMake(titleLb.right, titleLb.top, 200, titleLb.height);
    }
    _textField.backgroundColor = [UIColor clearColor];
    _textField.text = AudioName;
    _textField.placeholder = @"请输入标题";
    if (ISIPAD) {
        _textField.font = titleLb.font;
    } else {
        _textField.font = [UIFont systemFontOfSize:14.];
    }
    [topView addSubview:_textField];
    
    //换图视图*********************************
    UIView *changeImageView = [[UIView alloc] initWithFrame:CGRectMake(0, topView.bottom+20*PERCEN_HEIGHT, SCREEN_WIDTH, 140*PERCEN_HEIGHT)];
    changeImageView.backgroundColor = [UIColor whiteColor];
    [_tableView addSubview:changeImageView];
    
    UIImage *changImg = [UIImage imageNamed:@"huantu_fb"];
    UIButton *changeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.changeBtn = changeBtn;
    
    changeBtn.frame = CGRectMake(27*PERCEN, 14*PERCEN_HEIGHT, 80*PERCEN, 80*PERCEN);
    [changeBtn setImage:changImg forState:UIControlStateNormal];
    [changeImageView addSubview:changeBtn];
    [changeBtn addTarget:self action:@selector(changeClick) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *changeLb = [[UILabel alloc]initWithFrame:CGRectMake(25*PERCEN, changeBtn.bottom+10*PERCEN_HEIGHT, 200*PERCEN_HEIGHT, 20*PERCEN_HEIGHT)];
    changeLb.text = @"点击换图";
    changeLb.font = [UIFont systemFontOfSize:11.f];
    changeLb.textColor = UIColorFromHex(0x999999);
    [changeImageView addSubview:changeLb];
    
    //感受部分*********************************
    UIView *middleView = [[UIView alloc]initWithFrame:CGRectMake(0, changeImageView.bottom+20*PERCEN_HEIGHT, SCREEN_WIDTH, 300*PERCEN_HEIGHT)];
        [_tableView addSubview:middleView];
    middleView.backgroundColor = [UIColor whiteColor];
    //感受视图
    MBFeelView *feelView = [[MBFeelView alloc]initWithFrame:middleView.bounds];
    [middleView addSubview:feelView];
    feelView.backgroundColor = [UIColor whiteColor];
    //1.设置提醒文字
    feelView.myPlaceholder=@"随便写写现在的感受";
    //2.设置提醒文字颜色
    feelView.myPlaceholderColor=UIColorFromHex(0x999999);
    feelView.font = [UIFont systemFontOfSize:13.f];
    self.feelView = feelView;
  
    //亲子秀类型部分*********************************
    UILabel *showType = [[UILabel alloc] initWithFrame:CGRectMake(25*PERCEN, 20*PERCEN_HEIGHT+middleView.bottom, SCREEN_WIDTH, 20*PERCEN_HEIGHT)];
    showType.text = @"亲子秀类型";
    showType.textAlignment = NSTextAlignmentLeft;
    showType.font = [UIFont systemFontOfSize:13.f];
    [_tableView addSubview:showType];
    
    UIView *showTypeView = [[UIView alloc] initWithFrame:CGRectMake(0, showType.bottom+15*PERCEN, SCREEN_WIDTH, 160*PERCEN_HEIGHT)];
    [_tableView addSubview:showTypeView];
    showTypeView.backgroundColor = [UIColor whiteColor];
    
    UIImage *img = [UIImage imageNamed:@"weigouxuan_fb"];
    float itemWidth = showTypeView.height / 2.;
    for (int i=0; i<2; i++) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(25*PERCEN, (itemWidth-img.size.height)/2+i*itemWidth, img.size.width, img.size.height)];
        if (ISIPAD) {
            imgView.frame = CGRectMake(460*PERCEN, (itemWidth-img.size.height)/2+i*itemWidth, img.size.width, img.size.height);
        }
        _imgView = imgView;
        imgView.image = img;
        imgView.tag = 100+i;
        [showTypeView addSubview:imgView];
        UILabel *showLb = [[UILabel alloc] initWithFrame:CGRectMake(imgView.right+20*PERCEN,(itemWidth-img.size.height)/2+i*itemWidth , SCREEN_WIDTH, img.size.height)];
        if (ISIPAD) {
            showLb.frame = CGRectMake(imgView.right+20*PERCEN,(itemWidth-img.size.height)/2+i*itemWidth , SCREEN_WIDTH, img.size.height);
            showLb.font = [UIFont systemFontOfSize:15.f];
        }
        
        showLb.backgroundColor = [UIColor clearColor];
        showLb.textAlignment = NSTextAlignmentLeft;
        showLb.textColor = UIColorFromHex(0x333333);
        showLb.font = [UIFont systemFontOfSize:13.f];
        [showTypeView addSubview:showLb];
        
        
        UIButton *showBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _showBtn = showBtn;
        showBtn.backgroundColor = [UIColor clearColor];
        showBtn.frame = CGRectMake(0, i*itemWidth, SCREEN_WIDTH, itemWidth);
        [showBtn addTarget:self action:@selector(onSelectShowAction:) forControlEvents:UIControlEventTouchUpInside];
        showBtn.tag = i;
        [showTypeView addSubview:showBtn];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, itemWidth-1, SCREEN_WIDTH, 1)];
        if (ISIPAD) {
            lineView.frame = CGRectMake(440*PERCEN, itemWidth-1, 1168*PERCEN, 1);
        }
        lineView.backgroundColor = [UIColorFromHex(0xcccccc) colorWithAlphaComponent:.35];
        [showTypeView addSubview:lineView];
        
        if (i==0) {
            showLb.text = @"宝贝秀  (宝宝录制的作品)";
        }else {
            showLb.text = @"主播秀  (爸爸妈妈录制的作品)";
        }
        if (i == _identityType) {
            imgView.image = [UIImage imageNamed:@"gouxuan_fb"];
        }
    }
    
    if (ISIPAD) {
        topView.frame = CGRectMake(0, 0 ,SCREEN_WIDTH ,160*PERCEN );
        iconImageView.frame = CGRectMake(460*PERCEN, 20*PERCEN, 120*PERCEN, 120*PERCEN);
        titleLb.frame = CGRectMake(20*PERCEN+iconImageView.right, topView.height/2-10*PERCEN_HEIGHT, 300*PERCEN, 40*PERCEN_HEIGHT);
        titleLb.font = [UIFont systemFontOfSize:15.f];
        titleLb.textColor = UIColorFromHex(0x333333);
        
        changeImageView.frame = CGRectMake(0, topView.bottom+30*PERCEN_HEIGHT, SCREEN_WIDTH, 200*PERCEN);
        
        changImg = [UIImage imageNamed:@"huantu_"];
        changeBtn.frame = CGRectMake(460*PERCEN, 20*PERCEN, 120*PERCEN, 120*PERCEN);
        [changeBtn setImage:changImg forState:UIControlStateNormal];
        changeLb.frame = CGRectMake(460*PERCEN, changeImageView.height - 20*PERCEN-20, 120*PERCEN, 20);
        changeLb.textAlignment = NSTextAlignmentCenter;
        changeLb.font = [UIFont systemFontOfSize:12.f];
        changeLb.textColor = UIColorFromHex(0x999999);
        
        middleView.frame = CGRectMake(0, changeImageView.bottom+30*PERCEN, SCREEN_WIDTH, 300*PERCEN);
        
        feelView.frame = CGRectMake(440*PERCEN, 20*PERCEN, 1168*PERCEN, 260*PERCEN);
        feelView.layer.cornerRadius = 5.f;
        feelView.clipsToBounds = YES;
        feelView.font = [UIFont systemFontOfSize:15.f];
        feelView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        feelView.layer.borderWidth = 0.8f;
        feelView.delegate = self;
        UILabel *countLb = [[UILabel alloc] initWithFrame:CGRectMake(feelView.width-110, feelView.height-30, 100, 30)];
        [feelView addSubview:countLb];
        _countLb = countLb;
        countLb.text = @"0/300";
        countLb.textAlignment = NSTextAlignmentRight;
        countLb.textColor = [UIColor lightGrayColor];
       
        showType.frame = CGRectMake(460*PERCEN, 30*PERCEN+middleView.bottom, SCREEN_WIDTH, 20*PERCEN_HEIGHT);
        showType.font = [UIFont systemFontOfSize:14.f];

    }
    
    UIButton *sendPageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendPageBtn.frame = CGRectMake((SCREEN_WIDTH-400*PERCEN)/2, 80*PERCEN+showTypeView.bottom, 400*PERCEN, 80*PERCEN_HEIGHT);
    [sendPageBtn setBackgroundColor:TINK_BG_COLOR];
    [sendPageBtn setTitle:@"发布到个人主页" forState:UIControlStateNormal];
    [sendPageBtn addTarget:self action:@selector(sendChildShow) forControlEvents:UIControlEventTouchUpInside];
    [_tableView addSubview:sendPageBtn];
    sendPageBtn.layer.cornerRadius = 5.0f;
    sendPageBtn.clipsToBounds = YES;
    sendPageBtn.titleLabel.font = [UIFont systemFontOfSize:14.f];
    
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    saveBtn.frame =CGRectMake((SCREEN_WIDTH-200*PERCEN)/2, 40*PERCEN+sendPageBtn.bottom, 200*PERCEN, 80*PERCEN_HEIGHT);
    [saveBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [saveBtn setTitle:@"仅保存到本地" forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveLocalBtn) forControlEvents:UIControlEventTouchUpInside];
    [_tableView addSubview:saveBtn];
    
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:13.f];
    self.saveBtn = saveBtn;
    if (ISIPAD) {
        sendPageBtn.frame = CGRectMake((SCREEN_WIDTH-700*PERCEN)/2, 90*PERCEN+showTypeView.bottom, 700*PERCEN, 95*PERCEN);
        saveBtn.frame =CGRectMake((SCREEN_WIDTH-700*PERCEN)/2, 30*PERCEN+sendPageBtn.bottom, 700*PERCEN, 95*PERCEN_HEIGHT);
        saveBtn.layer.borderColor = UIColorFromHex(0xeb6fa7).CGColor;
        saveBtn.layer.borderWidth = 0.8f;
        saveBtn.tintColor = UIColorFromHex(0xeb6fa7);
        saveBtn.layer.cornerRadius = 5.0f;
        saveBtn.clipsToBounds = YES;
    }

}

#pragma mark - 播放音频
- (void)onChangePlauMusicStatus:(UIButton *)bt
{
    if (_recordPath.length == 0) return;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:_recordPath]) {
        
        bt.selected = !bt.selected;
        
//        if (bt.selected) {
//            //播放
//            NSURL *urlPath = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_recordPath]];
//            AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
//            if (!_audioPlayer) {
//                _audioPlayer = [[AVPlayer alloc]initWithPlayerItem:item];
//            } else {
//                [_audioPlayer replaceCurrentItemWithPlayerItem:item];
//            }
//            [_audioPlayer play];
//        } else {
//            //暂停
//            if (_audioPlayer) {
//                [_audioPlayer pause];
//            }
//        }
        
        
        if (!_audioPlayer) {
            _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:_recordPath] error:nil];
        }
        
        if (!_audioSession) {
            _audioSession = [AVAudioSession sharedInstance];
        }
        [_audioSession setActive:NO error:nil];
        [_audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

        
        if (bt.selected) {
            if ([UserManager standerDefult].mainPlayer && [UserManager standerDefult].isPlaying) {
                [[UserManager standerDefult].mainPlayer pause];
            }
            
            [_audioPlayer prepareToPlay];
            [_audioPlayer play];
            
    
        } else {
            if ([UserManager standerDefult].mainPlayer && [UserManager standerDefult].isPlaying) {
                [[UserManager standerDefult].mainPlayer play];
            }
            
            [_audioPlayer pause];

        }

    }
}

#pragma mark - 亲子秀类型
- (void)onSelectShowAction:(UIButton *)bt {
    
    if (bt.tag == _identityType) {
        return;
    }
    
    UIImageView *imgSelectView = (UIImageView *)[self.view viewWithTag:100+bt.tag];
    UIImageView *imgView = (UIImageView *)[self.view viewWithTag:100+_identityType];
    imgView.image = [UIImage imageNamed:@"weigouxuan_fb"];
    
    switch (bt.tag) {
        case 0:
        {
            imgSelectView.image = [UIImage imageNamed:@"gouxuan_fb"];
            _showType = @1;
        }break;
        case 1:
        {
            imgSelectView.image = [UIImage imageNamed:@"gouxuan_fb"];
            _showType = @2;
        }
            break;
        default:
            break;
    }
    _identityType = (int)bt.tag;
}

#pragma mark - 点击换图
//弹出相片选择框
- (void)changeClick
{
    if (IOS(8.0)) {
        UIAlertController *alertContr = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        __weak typeof(self) weakSelf = self;
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf onChooseType:UIImagePickerControllerSourceTypeCamera];
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从手机相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf onChooseType:UIImagePickerControllerSourceTypePhotoLibrary];
        }];
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertContr addAction:action1];
        [alertContr addAction:action2];
        [alertContr addAction:action3];
        [action1 setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        [action2 setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        [action3 setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        
        if (ISIPAD) {
            UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"打开照相机" otherButtonTitles:@"从手机相册获取", nil];
            [sheet showInView:self.view];
        } else {
            [self.navigationController presentViewController:alertContr animated:YES completion:NULL];
        }
    } else {
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"打开照相机" otherButtonTitles:@"从手机相册获取", nil];
        [sheet showInView:self.view];
    }
    
    }

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self onChooseType:UIImagePickerControllerSourceTypeCamera];
    }
    else if (buttonIndex == 1) {
        [self onChooseType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    else if (buttonIndex == 2) {
        
    }
}

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
    for (UIView *view in actionSheet.subviews) {
        if ([view isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel *)view;
            label.textColor = [UIColor blackColor];
        }
    }
}

#pragma mark - 相片
- (void)onChooseType:(UIImagePickerControllerSourceType)sourceType
{
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
            NSLog(@"该手机不能拍照");
            return;
        }
    }
    
    UIImagePickerController *pickerCtrl = [[UIImagePickerController alloc]init];
    pickerCtrl.sourceType = sourceType;
    pickerCtrl.delegate = self;
    pickerCtrl.allowsEditing = YES;
    
    if (ISIPAD) {
        pickerCtrl.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    
    if (ISIPAD) {
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            UIPopoverController *poc = [[UIPopoverController alloc]initWithContentViewController:pickerCtrl];
            poc.popoverContentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
            [poc presentPopoverFromRect:CGRectMake(0, 0, SCREEN_WIDTH, 40) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
        }];
    } else {
        [self.navigationController presentViewController:pickerCtrl animated:YES completion:NULL];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    if (info.count > 0) {
        UIImage *originImg = [info objectForKey:UIImagePickerControllerEditedImage];
        _showImg = [UIImage imageWithData:[self onGetPictureForIMG:originImg]];
        [self.changeBtn setImage:_showImg forState:UIControlStateNormal];
        if (ISIPAD) {
            [self.changeBtn setImage:_showImg forState:UIControlStateNormal];
        }
        
        [self.navigationController dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (NSData *)onGetPictureForIMG:(UIImage *)img
{
    CGRect rect = CGRectMake(0, 0, 300, 300);
    UIGraphicsBeginImageContext(rect.size);
    [img drawInRect:rect];
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImagePNGRepresentation(newImg);
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.navigationController dismissViewControllerAnimated:YES completion:NULL];
}


#pragma mark - 保存到本地
- (void)saveLocalBtn {
    
    if (_textField.text.length == 0) {
        [ErrorMessage showErrorMessage:@"请输入标题" inView:self.view];
        return;
    }
    else if (self.feelView.text.length == 0) {
        [ErrorMessage showErrorMessage:@"请输入现在的感受" inView:self.view];
        return;
    }

    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate:date];
    UserModel *model = [UserManager standerDefult].userModel;
    
    //音频
    NSString *mp3Path = @"";
    NSString *picPath = @"";
    NSString *sizeText = @"0";
    
    NSString *mp3FilePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",MUSIC_PRIVATE_NAME]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:mp3FilePath]) {
        NSString *newMp3FilePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",_textField.text]];
        
        if ([fileManager fileExistsAtPath:newMp3FilePath]) {
            newMp3FilePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",[NSString stringWithFormat:@"%@_%@",_textField.text,dateString]]];
        }
        mp3Path = newMp3FilePath;
        
        NSError *error;
        [fileManager copyItemAtPath:mp3FilePath toPath:newMp3FilePath error:&error];
        
        if (!error) {
            unsigned long long size = [fileManager attributesOfItemAtPath:newMp3FilePath error:nil].fileSize;
            sizeText = [NSString stringWithFormat:@"%.2f", size / pow(10, 6)];
            
            //保存图片
            if (_showImg) {
                NSString *newPicFilePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",_textField.text]];
                picPath = newPicFilePath;
                
                NSData *data = UIImagePNGRepresentation(_showImg);
                [data writeToFile:newPicFilePath atomically:YES];
            }
        }
    }
    
    //插入数据库
    //获取所有的取最好一个编号
    NSString *idStr = @"1";
    NSArray *allMusicArr = [[FMManageObject standerDefault]onSelectLocalParentChildShowCount];
    if (allMusicArr.count > 0) {
        NSDictionary *musciDic = [allMusicArr lastObject];
        idStr = [NSString stringWithFormat:@"%d",[[musciDic objectForKey:@"id"] intValue]+1];
    }
    
    NSMutableString *nick = [NSMutableString stringWithFormat:@"%@",model.NickName];
    if ([nick componentsSeparatedByString:@"'"].count >= 2) {
        [nick replaceOccurrencesOfString:@"'" withString:@" " options:1 range:NSMakeRange(0, nick.length)];
    }
    BOOL isOK = [[FMManageObject standerDefault]insertTableByLocalParentChildShowWithId:idStr withTitle:_textField.text withUserId:[NSString stringWithFormat:@"%@",model.UserID] withMusicId:@"0" withContent:(self.feelView.text.length > 0 ? self.feelView.text : @"") withType:[NSString stringWithFormat:@"7-%@",_showType] withPicture:picPath withDate:dateString withMp3:mp3Path withUserPic:[NSString stringWithFormat:@"%@",model.FaceImg] withUserNick:nick withSize:sizeText];
    if (isOK) {
         [self navigationBackButton];
    }
}

- (void)hideTheKeyBoard{
    [_textField resignFirstResponder];
    [self.feelView resignFirstResponder];

}

#pragma mark - 发布到个人主页
- (void)sendChildShow {
    
    //标题不能为空，感受不能为空，图片可以不换
    if (_textField.text.length == 0) {
        [ErrorMessage showErrorMessage:@"请输入标题" inView:self.view];
        return;
    }
    else if (self.feelView.text.length == 0) {
        [ErrorMessage showErrorMessage:@"请输入现在的感受" inView:self.view];
        return;
    }
    
    if (!_updateView) {
        _updateView = [[UpdateProgressView alloc]init];
        _updateView.delegate = self;
        [_updateView showInView:self.view];
    }
    _updateView.orientation = self.orientation;
    
    if (_picUrl.length == 0 ) {
        [self onUpdatPicture];
    }
    else if (_picUrl.length > 0 && _audioUrl.length == 0) {
        [self onUpdateMp3WithpicUrl:_picUrl];
    }
    else if (_picUrl.length > 0 && _audioUrl.length > 0) {
        [self onUpdateRequestWithMp3Url:_picUrl withPicUrl:_audioUrl];
    }
}

//上传图片
- (void)onUpdatPicture
{
    if (_showImg) {
        UIImage *img = _showImg;
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             nil];
        [manager POST:[NSString stringWithFormat:UPLOAD_FILE_URL_PATH,[UserManager standerDefult].userModel.UserID] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            NSData *data = UIImagePNGRepresentation(img);
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"HeaderImg_%@.png",dateString];
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"multipart/form-data"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
            CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
            if (progress <= 30) {
                _updateView.progress = progress;
            }
            
        } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                if ([[responseObject objectForKey:@"ret_code"]intValue] == 0) {
                    NSString *webUrl = [responseObject objectForKey:@"web_url"];
                    _picUrl = webUrl;
                    [self onUpdateMp3WithpicUrl:webUrl];
                } else {
                    [self onUpdateMp3WithpicUrl:@""];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self onUpdateMp3WithpicUrl:@""];
        }];
    } else {
        [self onUpdateMp3WithpicUrl:@""];
    }
}

//上传音频
- (void)onUpdateMp3WithpicUrl:(NSString *)picUrl
{
    if (_recordPath) {
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             nil];
        [manager POST:[NSString stringWithFormat:UPLOAD_FILE_URL_PATH,[UserManager standerDefult].userModel.UserID] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            NSData *data = [NSData dataWithContentsOfFile:_recordPath];
            [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"%@.mp3",_textField.text] mimeType:@"multipart/form-data"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
            CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;

            if (progress > 30) {
                _updateView.progress = progress;
            }
            
        } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                if ([[responseObject objectForKey:@"ret_code"]intValue] == 0) {
                    NSString *webUrl = [responseObject objectForKey:@"web_url"];
                    _audioUrl = webUrl;
                    NSString *Capacity	 = [responseObject objectForKey:@"Capacity"];
                    _capacity = [NSString stringWithFormat:@"%@",Capacity];
                    [self onUpdateRequestWithMp3Url:_audioUrl withPicUrl:picUrl];
                } else {
                    [_updateView onShowFaileContent:UpdateProgressViewType_Faile];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [_updateView onShowFaileContent:UpdateProgressViewType_Faile];
        }];
    }
}

- (void)onUpdateRequestWithMp3Url:(NSString *)mp3Url withPicUrl:(NSString *)picUrl
{
    UserModel *model = [UserManager standerDefult].userModel;
    NSString*url=[NSString stringWithFormat:FAMILYSHOW_ISSUESHOW_URL_PATH,model.UserID,_textField.text,picUrl,mp3Url,_capacity,(self.feelView.text.length > 0 ? self.feelView.text : @""),_showType,_activityId];

    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(id json) {
        
        if ([json[@"ret_code"] integerValue]==0) {
            _picUrl = @"";
            _audioUrl = @"";
            _capacity = @"";
            [_updateView onShowFaileContent:UpdateProgressViewType_Success];

        }
    } failure:^(NSError *error) {
        [_updateView onShowFaileContent:UpdateProgressViewType_Faile];
    }];

}

#pragma mark - TextView
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    int lengthCount = (int)(textView.text.length + text.length);
    if (lengthCount >= 151) {
        return NO;
    }
    _countLb.text = [NSString stringWithFormat:@"%d/300",lengthCount];
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    int lengthCount = (int)textView.text.length;
    if (lengthCount <= 300) {
        _countLb.text = [NSString stringWithFormat:@"%d/300",lengthCount];
    }
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    int lengthCount = (int)textView.text.length;
    if (lengthCount <= 300) {
        _countLb.text = [NSString stringWithFormat:@"%d/300",lengthCount];
    }
}


@end
